<template>
    <div class="box">
        <div class="lift item"></div>
        <div class="right item">
            <div class="top">
                <button @click="saveDataFn">保存当前配置到本地文件</button>
                <button @click="saveDefaultFn">恢复默认</button><br />
                factor：{{ factor }}<br />
                ctxTranslate:x{{ ctxTranslate.x }} ,y{{ ctxTranslate.y }}

            </div>
            <div class="bottom">
                <canvas id="canvasBg" width="1500" height="800"></canvas>
                <canvas id="canvasAGV" width="1500" height="800"></canvas>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { getAllAgvInfoApi, setFileInfoApi, getFileInfo } from "../../api/agv";
import mapData from "../../assets/0724.json";
var multiple = window.project.multiple  // 缩小倍数
let factor = ref(window.project.factor) // 滚轮放大缩小
let ctxTranslate = ref({
    x: window.project.ctxTranslate.x,
    y: window.project.ctxTranslate.y
})
let agvInterval;
let agvFn = () => {
    agvInterval = setInterval(() => {
        getCanvasAGV()
    }, 500);
}
let _agvDraw = () => {
    clearInterval(agvInterval) //一定要清除定时函数！！
    getCanvasBg()
    getCanvasAGV()
    agvFn()
}


let isDown = ref(false)

let prevX, prevY, currX, currY;
let velocityX, velocityY;
let prevTime;
// 控制缩放
let init = () => {
    // 滚轮滑动
    window.addEventListener("wheel", e => {
        if (e.target.id == "canvasAGV" || e.target.id == "canvasBg") {
            if (e.wheelDelta < 0) {
                // console.log("向下滚动！");
                factor.value -= 0.05;
                factor.value = factor.value <= 0.1 ? 0.1 : factor.value
                _agvDraw()
            } else {
                // console.log("向上滚动！");
                factor.value += 0.05;
                factor.value = factor.value >= 3 ? 3 : factor.value
                _agvDraw()
            }
        }

    });
    // 监听鼠标按下
    window.addEventListener("mousedown", e => {
        // 判断是否在bottom div中
        if (e.target.id == "canvasAGV" || e.target.id == "canvasBg") {
            console.log("鼠标按下！");
            isDown.value = true
            return;
        }
    });
    window.addEventListener('mousemove', e => {
        if (isDown.value) {
            currX = e.clientX;
            currY = e.clientY;
            if (prevX && prevY) {
                // 计算鼠标在X和Y方向上的速度
                velocityX = (currX - prevX) / (e.timeStamp - prevTime);
                velocityY = (currY - prevY) / (e.timeStamp - prevTime);
                ctxTranslate.value.x += velocityX * 10
                ctxTranslate.value.y += velocityY * 10
            }
            prevX = currX;
            prevY = currY;
            prevTime = e.timeStamp;
            _agvDraw()
        }
    })
    window.addEventListener('mouseup', e => {
        isDown.value = false
    })
}
let saveFactor = async (e) => {
    let res = await setFileInfoApi(e)
    if (res.success) {
        alert("保存成功！")
    } else {
        alert("保存失败！")
    }
}
let saveDataFn = () => {
    let saveData = {
        factor: factor.value,
        ctxTranslate: ctxTranslate.value
    }
    saveFactor(saveData)
}
let saveDefaultFn = async () => {
    let def = {
        factor: window.project.factor,
        ctxTranslate: window.project.ctxTranslate
    }
    saveFactor(def).then(() => {
        location.reload()
    })
    
}
// 获取canvas
const canvasBg = ref(null);
const canvasAGV = ref(null);
let getCanvasAGV = async () => {
    // 获取小车位置信息
    let carxy = []
    let data = { reqCode: 1 }
    await getAllAgvInfoApi(data).then((res) => {
        for (let i in res.data) {
            carxy.push(res.data[i])
        }
    })
    canvasAGV.value = document.getElementById('canvasAGV');
    let canvas = canvasAGV.value
    let ctx = canvas.getContext('2d');
    canvas.width = canvas.width
    ctx.translate(ctxTranslate.value.x, ctxTranslate.value.y);
    ctx.scale(factor.value, factor.value);
    ctx.scale(1, -1) // 反转坐标轴
    ctx.fillStyle = "red";
    for (let i in carxy) {
        // 旋转
        ctx.save()
        ctx.translate(carxy[i].x / multiple - 10, carxy[i].y / multiple - 10)
        // 绘制文字
        ctx.scale(1, -1)
        ctx.fillStyle = '#222'
        ctx.font = ' bold 15px 微软雅黑'
        ctx.fillText(carxy[i].name, -15, 15)
        ctx.scale(1, -1)
        // 绘制正方形4
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(20, 0);
        ctx.lineTo(20, 20);
        ctx.lineTo(0, 20);
        ctx.closePath();
        ctx.fillStyle = "royalblue";
        ctx.fill();

        // 恢复坐标轴
        ctx.restore()
    }
}
let getCanvasBg = () => {
    canvasBg.value = document.getElementById('canvasBg');
    let canvas = canvasBg.value
    let ctx = canvas.getContext('2d');
    canvas.width = canvas.width
    ctx.translate(ctxTranslate.value.x, ctxTranslate.value.y);
    ctx.scale(1, -1) // 反转坐标轴
    ctx.scale(factor.value, factor.value);
    ctx.fillStyle = "red";
    // 绘制站点
    for (let i in mapData.Sites) {
        //console.log(Math.round(mapData.Sites[i].x / multiple - 5), Math.round(mapData.Sites[i].y / multiple - 5))
        ctx.fillRect(Math.round(mapData.Sites[i].x / multiple - 5), Math.round(mapData.Sites[i].y / multiple - 5), 10, 10);
        // 添加描边，解决两个点相邻太近问题
        ctx.strokeStyle = "#fff"; // 描边颜色
        ctx.lineWidth = 1; // 描边线宽
        ctx.strokeRect(Math.round(mapData.Sites[i].x / multiple - 5), Math.round(mapData.Sites[i].y / multiple - 5), 10, 10);
    }
    // 创建路径
    let arr = [];
    let x1, y1, x2, y2 = Number //坐标
    for (let [key, value] of Object.entries(mapData.Tracks)) {
        // arr.push(value.siteA)
        let arr2 = {
            siteA: value.siteA,
            siteB: value.siteB
        }
        arr.push(arr2)
    }
    for (let i in arr) {
        // 获取Sites 中对应A-B的id 的key
        for (let j in mapData.Sites) {
            // 起点 
            if (arr[i].siteA == mapData.Sites[j].id) {
                x1 = mapData.Sites[j].x / multiple
                y1 = mapData.Sites[j].y / multiple
            }
        }
        for (let j in mapData.Sites) {
            // 终点 
            if (arr[i].siteB == mapData.Sites[j].id) {
                x2 = mapData.Sites[j].x / multiple
                y2 = mapData.Sites[j].y / multiple
            }
        }
        // 绘制路径
        ctx.beginPath(); //新建一条path
        ctx.moveTo(x1, y1); //把画笔移动到指定的坐标
        ctx.lineTo(x2, y2);  //绘制一条从当前位置到指定坐标的直线.
        ctx.lineWidth = 3; // 描边线宽
        //闭合路径。会拉一条从当前点到path起始点的直线。如果当前点与起始点重合，则什么都不做
        // ctx.closePath(); 
        // 路径颜色
        ctx.strokeStyle = "#555";
        ctx.stroke(); //绘制路径。
    }
}
onMounted(async () => {
    // 获取地图比例信息
    try {
        // 可以请求到数据
        let res = await getFileInfo()
        factor.value = res.data.factor
        ctxTranslate.value = res.data.ctxTranslate
    } catch {
        // '获取失败,取默认值'
        factor = ref(window.project.factor) 
        ctxTranslate = ref({
            x: window.project.ctxTranslate.x,
            y: window.project.ctxTranslate.y
        })
    }
    getCanvasBg()
    agvFn()
    init()
})
onBeforeUnmount(() => {
    // 卸载函数init()
})
</script>


<style scoped>
.box {
    height: 100vh;
    display: flex;
}

.lift {
    width: 300px;
    height: 100%;
    border-right: #999 1px solid;
    box-sizing: border-box;
}

.top {
    height: 80px;
    width: calc(100vw - 300px);
    border-bottom: #999 1px solid;
    box-sizing: border-box;
}

.bottom {
    height: calc(100vh - 80px);
    width: calc(100vw - 300px);
    position: relative;
}

#canvasBg {
    width: calc(100vw - 300px);
    height: calc(100vh - 84px);
    position: absolute;
    top: 0px;
    left: 0px;
}

#canvasAGV {
    width: calc(100vw - 300px);
    height: calc(100vh - 84px);
    position: absolute;
    top: 0px;
    left: 0px;
}
</style>